package org.ithasu.tools.net.transmission;

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import org.ithasu.tools.Console;
import org.ithasu.tools.IOTools;
import org.ithasu.tools.net.JSONTools;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class TransmissionConnector {

	private final static String SESSION_ID = "X-Transmission-Session-Id";

	protected URL serverUrl;
	protected String sessionId;

	public TransmissionConnector(String url) {
		try {
			// Prepare URL
			this.serverUrl = new URL(url);
			// Fetch session id
			URLConnection connection = serverUrl.openConnection();
			sessionId = connection.getHeaderField(SESSION_ID);
		} catch (Exception e) {
			Console.error(e);
			this.serverUrl = null;
		}
	}

	public JSONObject getTorrents() {
		try {
			JSONArray fields = new JSONArray();
			fields.add("name");
			JSONObject args = new JSONObject();
			args.put("fields", fields);
			JSONObject request = new JSONObject();
			request.put("arguments", args);
			request.put("method", "torrent-get");

			URLConnection connection = serverUrl.openConnection();
			connection.setDoOutput(true);
			String data = request.toString();

			if (sessionId != null) {
				connection.setRequestProperty(SESSION_ID, sessionId);
			}
			//			connection.setRequestProperty("Content-length", String.valueOf(data.length()));

			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream());
			Console.message(data);
			out.write(data);//URLEncoder.encode(data, "UTF-8"));
			out.close();

			JSONParser p = new JSONParser();
			String decodedString = new String(IOTools.read(connection.getInputStream()));
			return JSONTools.safeCast(JSONObject.class, p.parse(decodedString));
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	public void addTorrent(String torrent) {
		try {
			JSONObject args = new JSONObject();
			args.put("filename", torrent);
			JSONObject request = new JSONObject();
			//			request.put("arguments", args);
			request.put("method", "torrent-get");

			URLConnection connection = serverUrl.openConnection();
			connection.setDoOutput(true);
			String data = request.toString();

			if (sessionId != null) {
				connection.setRequestProperty(SESSION_ID, sessionId);
			}
			//			connection.setRequestProperty("Content-length", String.valueOf(data.length()));

			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream());
			Console.message(data);
			out.write(data);//URLEncoder.encode(data, "UTF-8"));
			out.close();

			String decodedString = new String(IOTools.read(connection.getInputStream()));
			Console.message(decodedString);
		} catch (Exception e) {
			Console.error(e);
		}
	}

}
